package dk.mga.androidExplore.wifi;
import java.util.Iterator;
import java.util.List;

import dk.mga.androidExplore.R;
import android.app.Activity;
import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;


public class WiFiAnalyzer extends Activity {

	private String tag = "myLog";
	private final int UPDATE_INTERVAL = 1000; // 1 second
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
    	setContentView(R.layout.monitor_wifi);
		TableLayout tl = (TableLayout) findViewById(R.id.TableLayout01);
		TableRow tr = new TableRow(this);
		for (int cnt = 0; cnt < 4; cnt++){
			TextView tv = new TextView(this);
			tv.setPadding(5, 0, 5, 0);
			tr.addView(tv);
		}
		tl.addView(tr);
		
		updateWifiScan();
				
	}

	Handler handler = new Handler();
	
	Runnable updateTask = new Runnable() {
		@Override
		public void run() {
			updateWifiScan();
			handler.postDelayed(this, UPDATE_INTERVAL);
		}
	};
	
	private void updateWifiScan() {
		TableLayout tl = (TableLayout) findViewById(R.id.TableLayout01);
		while (tl.getChildCount() > 1) {
			tl.removeViewAt(1);
		}
		Log.d(tag, "updating wifi");
		WifiManager wm = (WifiManager )getSystemService(Context.WIFI_SERVICE);
		List<ScanResult> srList = wm.getScanResults();
		wm.startScan();
		if (srList != null) {
			Iterator<ScanResult> i = srList.iterator();
			StringBuffer sb = new StringBuffer();
			sb.append("Wifi results:\n");
			while (i.hasNext()) {
				TableRow tr = new TableRow(this);
				for (int cnt = 0; cnt < 4; cnt++){
					TextView tv = new TextView(this);
					tv.setPadding(5, 0, 5, 0);
					tr.addView(tv);
				}
				Log.d(tag, "som tr?"+tr.toString());
				ScanResult sr = i.next();
				if (tr == null) {Log.d(tag, "tr == null"); return;}
				if (tr.getChildCount() == 0) {Log.d(tag, "tr.getChildCount() == 0"); return;}
				if (tr.getChildAt(0) == null) {Log.d(tag, "tr.getChildAt(0) == null"); return;}
				((TextView) tr.getChildAt(0)).setText(sr.SSID+"\n");
				((TextView) tr.getChildAt(1)).setText(sr.BSSID+"\n");
				((TextView) tr.getChildAt(2)).setText(""+sr.frequency+"\n");
				((TextView) tr.getChildAt(3)).setText(""+sr.level+"\n");
				tl.addView(tr);
				sb.append("\tBSSID="+sr.BSSID + '\n');
				sb.append("\tSSID="+sr.SSID + '\n');
				sb.append("\tCapabilities:"+sr.capabilities + '\n');
				sb.append("\tFrequense="+sr.frequency + '\n');
				sb.append("\tLevel"+sr.level + '\n');
			}
			Log.d(tag, sb.toString());
		} else {
			Log.d(tag, "List is NULL");
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		handler.postDelayed(updateTask, UPDATE_INTERVAL);
	}

	@Override
	protected void onPause() {
		super.onPause();
		handler.removeCallbacks(updateTask);
	}
	
}
